use crate::core::entity::whitelist_key::WhitelistKey;
use crate::core::model::resource_version_entry::ResourceVersionEntry;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// 白名单
#[derive(Default, Clone, Debug)]
pub struct Whitelist {
    map: Arc<RwLock<HashMap<WhitelistKey, ResourceVersionEntry>>>,
}

impl Whitelist {
    pub fn new() -> Self {
        Self {
            map: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub fn from(key: WhitelistKey, value: ResourceVersionEntry) -> Self {
        Self {
            map: Arc::new(RwLock::new(HashMap::from([(key, value)]))),
        }
    }

    pub fn insert(
        &self,
        key: WhitelistKey,
        resource_version_entry: ResourceVersionEntry,
    ) -> Option<ResourceVersionEntry> {
        self.map
            .write()
            .unwrap()
            .insert(key, resource_version_entry)
    }

    pub fn get(&self, key: &WhitelistKey) -> Option<ResourceVersionEntry> {
        self.map.read().unwrap().get(key).cloned()
    }

    pub fn get_all(&self) -> HashMap<WhitelistKey, ResourceVersionEntry> {
        self.map.read().unwrap().clone()
    }

    pub fn remove(&self, key: &WhitelistKey) -> Option<ResourceVersionEntry> {
        self.map.write().unwrap().remove(key)
    }

    pub fn clear(&self) {
        self.map.write().unwrap().clear();
    }
}
